<template>
  <el-card>
    <el-button type="primary" size="default" icon="Plus" @click="addTrademark">
      添加品牌
    </el-button>
    <el-table border style="width: 100%" :data="trademarkArr">
      <el-table-column
        label="序号"
        width="80"
        align="center"
        type="index"
      ></el-table-column>
      <el-table-column label="品牌名称">
        <template #="{ row, $index }">
          <pre>{{ row.tmName }}</pre>
        </template>
      </el-table-column>
      <el-table-column label="品牌LOGO">
        <template #="{ row, $index }">
          <img
            :src="row.logoUrl"
            alt="图片未显示"
            style="width: 100px; height: 100px"
          />
        </template>
      </el-table-column>
      <el-table-column label="品牌操作">
        <template v-slot="{ row, $index }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="updateTrademark(row)"
          ></el-button>
          <el-popconfirm
            :title="`你确定删除${row.tmName}品牌吗？`"
            width="250px"
            icon="Delete"
            @confirm="removeTrademark(row.id)"
          >
            <template #reference>
              <el-button type="primary" size="small" icon="Delete"></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页器-->
    <el-pagination
      @size-change="Trademark"
      @current-change="Trademark"
      v-model:current-page="PageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 7, 10, 12]"
      :background="true"
      layout="prev, pager, next, jumper,->, sizes,total"
      :total="total"
    />
  </el-card>

  <!--  对话框-->
  <el-dialog
    v-model="dialogVisible"
    :title="trademarkPamr.id ? '修改品牌' : '添加品牌'"
  >
    <el-form
      style="width: 80%"
      :model="trademarkPamr"
      :rules="rules"
      ref="fomRef"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          placeholder="请输入品牌的名称"
          v-model="trademarkPamr.tmName"
        ></el-input>
      </el-form-item>
      <el-form-item label="品牌LOGO" prop="logoUrl">
        <!--     上传-->
        <el-upload
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img
            v-if="trademarkPamr.logoUrl"
            :src="trademarkPamr.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" size="small" @click="Cancel">取消</el-button>
      <el-button size="small" @click="Confirm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
//品牌管理的接口
import {
  reqTrademark,
  reqAddOrUpdateTrademark,
  reqDelete,
} from '@/api/product/teademark'
import { ElMessage } from 'element-plus'

//当前页码
let PageNo = ref<number>(1)
//每一页显示多少条数据
let limit = ref<number>(3)
//总条数
let total = ref<number>(0)
//控制对话框的显示与隐藏
let dialogVisible = ref<boolean>(false)
//存储已有品牌的数据
let trademarkArr = ref<any>([])
//收集图片名称与logo地址
let trademarkPamr = reactive<any>({
  tmName: '',
  logoUrl: '',
})
//el-form
let fomRef = ref<any>()
//获取已有品牌接口封装为一个函数
const Trademark = async (pager = 1) => {
  PageNo.value = pager
  let result: any = await reqTrademark(PageNo.value, limit.value)
  if (result.code == 200) {
    total.value = result.data.total
    trademarkArr.value = result.data.records
  }
}
//组件加载完毕就发一次请求
onMounted(() => {
  Trademark()
})
//添加品牌
const addTrademark = () => {
  //打开对话框
  dialogVisible.value = true
  //  清除品牌名称和品牌图片
  trademarkPamr.tmName = ''
  trademarkPamr.logoUrl = ''
  trademarkPamr.id = 0
  //  第一种写法
  //清除留下的规则痕迹
  // fomRef.value?.clearValidate('tmName')
  // fomRef.value?.clearValidate('logoUrl')
  //第二种写法
  nextTick(() => {
    fomRef.value.clearValidate('tmName')
    fomRef.value.clearValidate('tmName')
  })
}
//修改品牌
const updateTrademark = (row: any) => {
  //打开对话框
  dialogVisible.value = true
  trademarkPamr.id = row.id
  trademarkPamr.logoUrl = row.logoUrl
  trademarkPamr.tmName = row.tmName

  // Object.assign(trademarkPamr,row)

  //  修改图片这里也要清除规则留下的痕迹
  nextTick(() => {
    fomRef.value.clearValidate('tmName')
    fomRef.value.clearValidate('tmName')
  })
}

//对话框底部的取消
const Cancel = () => {
  //关闭对话框
  dialogVisible.value = false
}
//对话框底部的确认
const Confirm = async () => {
  // 发送请求前要对整个进行验证
  //对整个表单进行验证
  await fomRef.value.validate()
  let result: any = await reqAddOrUpdateTrademark(trademarkPamr)
  if (result.code == 200) {
    //关闭对话框
    dialogVisible.value = false
    //  弹出添加品牌提示的信息
    ElMessage({
      type: 'success',
      message: trademarkPamr.id ? '修改品牌成功' : '添加品牌成功',
    })
    // 重新获取数据
    Trademark()
  } else {
    ElMessage({
      type: 'error',
      message: trademarkPamr.id ? '修改品牌失败' : '添加品牌失败',
    })
    //关闭对话框
    dialogVisible.value = false
  }
}

//上传图片的规则
const beforeAvatarUpload: any['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/jpg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 < 4) {
      return true
    } else {
      ElMessage({
        type: 'error',
        message: '上传的图片大笔大于4M',
      })
      return false
    }
  } else {
    ElMessage({
      type: 'error',
      message: '上传的图片必须是jpg|png|gif',
    })
    return false
  }
}
//上传图片
const handleAvatarSuccess: any['onSuccess'] = (response, uploadFile) => {
  //收集图片上传地址，添加一个新的品牌，然后带给服务器
  trademarkPamr.logoUrl = response.data
  //上传图片之前也要对图片进行清除
  fomRef.value.clearValidate('logoUrl')
}

//图片名称的自定义检验
const validatortTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length >= 2) {
    callBack()
  } else {
    callBack(new Error('图片的名称必须大于两位'))
  }
}
//图片的自定义的规则
const validatortLogoUrl = (rule: any, value, callBack: any) => {
  if (value) {
    callBack()
  } else {
    callBack(new Error('必须上传图片'))
  }
}

//表单校验对象
const rules = {
  tmName: [{ required: true, trigger: 'blur', validator: validatortTmName }],
  logoUrl: [{ required: true, trigger: 'blur', validator: validatortLogoUrl }],
}

//删除已有的品牌
const removeTrademark = async (id) => {
  let result = await reqDelete(id)
  console.log(result.id)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '成功',
    })
    Trademark()
  } else {
    ElMessage({
      type: 'error',
      message: '失败',
    })
  }
}
</script>
<script lang="ts">
export default {
  name: 'teadmark',
}
</script>

<style scoped lang="scss">
.demo-pagination-block + .demo-pagination-block {
  margin-top: 10px;
}
.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}
//上传的样式

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
